import Vue from "vue";
const uuid = require("uuid");
// import uuid from 'uuid'
// import locale from 'element-ui/lib/locale/lang/en'
export default () => {
  // 注册一个全局自定义指令 `v-command`
  Vue.directive("command", {
    // 当被绑定的元素插入到 DOM 中时……
    update: function(el, binding) {
      console.debug("update");
      // 聚焦元素
      console.debug("command show control =========");
      // var pbp = JSON.parse(localStorage.getItem('pageButtonPower') || '{}')
      // let resources = pbp.result || []
      // let compare = []
      // resources.forEach((v, k) => {
      //   compare.push(v.resourceEname)
      // })
      // if (compare.indexOf(binding.value) == -1) {
      //   // el.style.display = 'none'
      //   el.remove()
      // }
      var user = JSON.parse(localStorage.getItem("user") || {});
      const resources = user.resources || "";
      const res = resources.indexOf(binding.value) > -1;
      if (!res) el.style.display = "none";
    }
  });

  Vue.directive("isrc", {
    // 当被绑定的元素插入到 DOM 中时……
    update: function(el, binding) {
      // 聚焦元素
      const url = window.$nuxt.$store.state.baseUrl + "/" + binding.value;
      el.src = url;
    }
  });

  // let page = 3
  function getDataPage(el) {
    console.debug("prepare tag directive");
    var page = "";
    if (!el.childNodes || el.childNodes.length < 1 || el.dataset) {
      return el.dataset.page;
    }
    for (var i = 0; i < el.childNodes.length; i++) {
      var child = el.childNodes[i];
      if (child.childNodes && child.childNodes.length > 0) {
        var tmp = getDataPage(child);
        if (tmp && tmp.length > 1) {
          page = tmp;
          break;
        }
      } else {
        if (child.dataset && child.dataset.page) {
          page = child.dataset.page;
          break;
        }
      }
    }
    return page;
  }

  Vue.directive("tag", {
    // 当被绑定的元素插入到 DOM 中时……
    bind: function(el, binding) {
      console.debug("tag binding ... ");
      // 聚焦元素
      console.debug(binding.arg + ": tag");
      // 指令所在的页面
      // var page = el.dataset.page
      var page = getDataPage(el);
      // 如果没传入页面，则视为无效的绑定
      if (!page) return;
      // 是消息还是tag
      var type = binding.arg + "s";
      // 存储的当前页面的消息
      // pageItem 格式如下
      // pageItem = {tags:[{name: '', ts: 0}], msgs: [{name: '', ts: 0}]}
      var pageItem = JSON.parse(localStorage.getItem("hmi/" + page) || "{}");
      // tag名
      var tagName = binding.value;
      // 如果该页面没有需要从后台取数的变量，那么直接更新
      if (!pageItem[type]) {
        if (!pageItem) pageItem = {};
        pageItem[type] = [];
        var obj = {
          tagName: tagName,
          timestamp: 0
        };
        if (type === "msgs") {
          obj.ticket = uuid.v4().replace(new RegExp("-", "g"), "");
          obj.id = tagName;
          obj.reply = true;
          obj.timeout = 0;
        }
        pageItem[type][0] = obj;
        localStorage.setItem("hmi/" + page, JSON.stringify(pageItem));
      } else {
        // 判断原有集合中是否已经包含变量名
        const exist = pageItem[type].some(o => {
          return o.tagName === tagName;
        });
        // 如果已经包含了，不用加入任何信息
        if (exist) return;
        // 如果没有包含，则将变量名加入列表
        else {
          var obj1 = {
            tagName: tagName,
            timestamp: 0
          };
          if (type === "msgs") {
            obj.ticket = uuid.v4().replace(new RegExp("-", "g"), "");
            obj.id = tagName;
            obj.reply = true;
            obj.timeout = 0;
          }
          pageItem[type].push(obj1);
        }
        // 更新当前页面的变量列表项
        localStorage.setItem("hmi/" + page, JSON.stringify(pageItem));
      }
    }
  });

  // v-dialogDrag: 弹窗拖拽
  Vue.directive("dialogDrag", {
    bind(el, binding, vnode, oldVnode) {
      const dialogHeaderEl = el.querySelector(".el-dialog__header");
      const dragDom = el.querySelector(".el-dialog");
      dialogHeaderEl.style.cursor = "move";

      // 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
      const sty =
        dragDom.currentStyle || window.getComputedStyle(dragDom, null);

      dialogHeaderEl.onmousedown = e => {
        // 鼠标按下，计算当前元素距离可视区的距离
        const disX = e.clientX - dialogHeaderEl.offsetLeft;
        // const disY = e.clientY - dialogHeaderEl.offsetTop

        // 获取到的值带px 正则匹配替换
        let styL;
        // let styT

        // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
        if (sty.left.includes("%")) {
          styL =
            +document.body.clientWidth * (+sty.left.replace(/\%/g, "") / 100);
          // styT =+document.body.clientHeight * (+sty.top.replace(/\%/g, '') / 100)
        } else {
          styL = +sty.left.replace(/\px/g, "");
          // styT = +sty.top.replace(/\px/g, '')
        }

        document.onmousemove = function(e) {
          // 通过事件委托，计算移动的距离
          const l = e.clientX - disX;
          // const t = e.clientY - disY

          // 移动当前元素
          dragDom.style.left = `${l + styL}px`;
          // dragDom.style.top = `${t + styT}px`

          // 将此时的位置传出去
          // binding.value({x:e.pageX,y:e.pageY})
        };

        document.onmouseup = function(e) {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    }
  });

  // v-dialogDragWidth: 弹窗宽度拖大 拖小
  Vue.directive("dialogDragWidth", {
    bind(el, binding, vnode, oldVnode) {
      const dragDom = binding.value.$el.querySelector(".el-dialog");

      el.onmousedown = e => {
        // 鼠标按下，计算当前元素距离可视区的距离
        const disX = e.clientX - el.offsetLeft;

        document.onmousemove = function(e) {
          e.preventDefault(); // 移动时禁用默认事件

          // 通过事件委托，计算移动的距离
          const l = e.clientX - disX;
          dragDom.style.width = `${l}px`;
        };

        document.onmouseup = function(e) {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    }
  });
  Vue.directive("draggable", {
    bind: function(el, binding, vnode) {
      var isDragging = false;
      var offsetX = 0;
      var offsetY = 0;

      el.addEventListener("mousedown", function(event) {
        isDragging = true;
        offsetX = event.clientX - el.offsetLeft;
        offsetY = event.clientY - el.offsetTop;
      });

      document.addEventListener("mousemove", function(event) {
        if (isDragging) {
          var left = event.clientX - offsetX;
          var top = event.clientY - offsetY;

          el.style.left = left + "px";
          el.style.top = top + "px";

          vnode.context.left = left;
          vnode.context.top = top;
        }
      });

      document.addEventListener("mouseup", function(event) {
        isDragging = false;
      });
    }
  });
};
